/*
 * cm_memory.c
 *
 *  Created on: 2015年9月1日
 *      Author: chens
 */

#include <pthread.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>

#include "cm_buddy_alg.h"
#include "cm_memory.h"

static struct {
    struct buddy2 * buddy;
    pthread_mutex_t lock;
    void * base;
    unsigned size;
} g_memory = { NULL, PTHREAD_MUTEX_INITIALIZER, NULL, 0 };

#define LOCK    pthread_mutex_lock(&(g_memory.lock))
#define UNLOCK    pthread_mutex_unlock(&(g_memory.lock))

/*
 * @brief   初始化内存模块
 * @param   base， size 用于内存管理的起始地址以及总的内存大小
 *          由于目前buddy只支持管理2的幂次个内存块， 因此 size / CM_MEM_BLOCK_SIZE
 *          将只取 2的幂次部分
 */
void cm_memory_setup(void *base, unsigned size)
{
    LOCK;
    if(g_memory.base != NULL || base == NULL || size <= CM_MEM_BLOCK_SIZE)
        return;

    int total = size / CM_MEM_BLOCK_SIZE;
    total = min_power_of_2_eg(total);
    g_memory.buddy = buddy2_new(total);

    UNLOCK;
}

/*
 * @brief   分配size个内存
 * @return  成功返回非NULL 失败返回NULL
 */
void * cm_malloc(unsigned size)
{
    return NULL;
}

/*
 * @brief   释放由 cm_malloc 分配的内存
 */
void cm_free(void *ptr)
{
}

